<template>
  <!-- EditPersonCard 编辑个人名片 -->
  <PageContainer>
    <view class="container">
      <Header
        title="编辑个人名片"
        :is-box-shadow="false"
        :enable-navigate-back-options="backOptions"
      />
      <Box>
        <PersonalInfo v-model:personal-info="personalInfo" />
      </Box>
      <Box title="社会荣誉">
        <FormHonor
          :tag-flex="true"
          v-model="personalHonorList"
          label="荣誉"
          placeholder="例：XX影响力人物、XX卓越领袖、XX先进工作者、XX优秀党员"
        />
      </Box>
      <Box title="社会职务">
        <FormHonor
          v-model="socialIdentityList"
          label="职务"
          :tag-flex="true"
          placeholder="例：XX政协委员、XX商会会长、XX专家顾问、XX学院教授"
        />
      </Box>
      <Box title="个人简介" :content-p-top="30">
        <ElegantDemeanour v-model="imgList" :is-edit="true" :card-type="ApplyTypeEnum.PERSON" />
        <CuttingLine />
        <UploadVideo :isEdit="isEdit" v-model="videoInfo" />
        <CuttingLine />
        <Introduction
          v-model="briefIntroduction"
          :isEdit="isEdit"
          :card-type="ApplyTypeEnum.PERSON"
        />
      </Box>
      <!-- 选择单位  :des="getMasterDes" -->
      <Box title="我的单位">
        <view class="affiliated-companies">
          <template v-for="(v, i) in getCompaniesDtoList" :key="i">
            <view class="affiliated-companies-item">
              <view class="companies-name">
                <text class="text-overflow-1 name">{{ v.name || '暂无单位名称' }}</text>
                <text v-if="v.authentication" class="tag">已认证</text>
                <text v-if="v.authentication" class="ali-icon ml-3" style="color: #808080" @click="showTips">&#xe6c9;</text>
              </view>
              <view class="handle-btn-group">
                <image
                  v-if="
                    (!v.authentication && v.id) ||
                    (v.id === cocInfo.cocId && getAuthenticationEditPer)
                  "
                  class="handle-btn"
                  @click="toEdit(v.id, v.authentication)"
                  src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/edit-icon.png"
                  mode="scaleToFill"
                />
                <image
                  v-if="!v.authentication && v.id"
                  class="handle-btn"
                  @click="toDel(i, v.id)"
                  src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/del-icon.png"
                  mode="scaleToFill"
                />
              </view>
            </view>
          </template>
          <TButton
            text="添加"
            icon="&#xe61f;"
            :customStyle="{
              backgroundColor: '#f5f5f5',
              border: '2rpx dashed #dddddd',
              color: '#808080',
            }"
            @click="openModel"
          />
        </view>
      </Box>
      <Box v-if="userInfo.isOpenMall" title="精选产品">
        <ChooseProducts v-model="selectedProductIds" :member-leading-id="memberLeadingId" />
      </Box>

      <TButtonGroup>
        <TButton class="gutter-btn" text="取消" custom-class="cardBlackBtn" @click="cancel" />
        <TButton class="gutter-btn" text="保存" custom-class="cardBtn" @click="submit" />
      </TButtonGroup>

      <UniPopup
        ref="SelectUnits"
        borderRadius="32rpx 32rpx 0 0"
        backgroundColor="#fff"
        @maskClick="maskClick"
      >
        <view class="select-units">
          <view class="select-units--header">
            <text>选择单位</text>
            <button class="add-btn" type="none" @click="addUnit">新增单位</button>
          </view>
          <scroll-view class="unit-list" scroll-y>
            <UniDataCheckbox
              v-model="temSelected"
              mode="list"
              :multiple="true"
              :wrap="true"
              :localdata="unitLocaldata"
            />
          </scroll-view>
          <TButton class="gutter-btn" text="确定" custom-class="cardBtn" @click="closeModel" />
        </view>
      </UniPopup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  EditPersonCard  编辑个人名片 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { computed, getCurrentInstance, nextTick, ref, unref } from 'vue';
  import { navigateTo, onLoad } from '@/router';
  import { editPersonalCardDetails, getCardPersonalSelectedProductIds } from '@/api/card';
  import {
    type EditPersonalCardDetailsData,
    type PersonalCardDetailsResult,
  } from '@/api/card/types';
  import PersonalInfo, { type PersonalInfoData } from './components/PersonalInfo.vue';
  import FormHonor from '@/components/Form/components/FormHonor.vue';
  import Box from '../components/box/index.vue';
  import ElegantDemeanour from '../components/elegantDemeanour/index.vue';
  import { ApplyTypeEnum } from '@/enums/membershipEnum';
  import CuttingLine from '../components/cuttingLine/index.vue';
  import UploadVideo from '../components/uploadVideo/index.vue';
  import Introduction from '../components/introduction/index.vue';
  import { Toast } from '@/utils';
  import { useBackBeforeUnload, type UseNavigateBackOptions } from '@/hooks/core/useNavigateBack';
  import { useLocation } from '@/hooks/core/useLocation';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { logManager } from '@/utils/log';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import UniDataCheckbox from '@/components/Form/uni_modules/uni-data-checkbox/uni-data-checkbox.vue';
  import type { Localdata } from '@/components/Form/types';
  import { storeToRefs } from 'pinia';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { MemberRoleEnum } from '@/enums/memberRoleEnum';
  import ChooseProducts from '../components/chooseProducts/index.vue';

  interface CompaniesDtoList {
    id: number;
    name: string;
    authentication: boolean;
  }

  const lPainterRef = ref<LPainterRef>();
  const isEdit = ref(true);
  const info = ref<PersonalCardDetailsResult>();

  const { canvasType } = useAppStoreWithOut();
  const useUser = useUserStoreWithOut();
  const { unitList, cocInfo, userInfo } = storeToRefs(useUser);

  const backOptions = ref<UseNavigateBackOptions>({
    enableBeforeUnload: true,
    showModalOptions: {
      content: '确认返回'
    },
  });

  const { interceptNavigateBack, UniNavigateBack } = useBackBeforeUnload(backOptions.value);

  const { parseAddress } = useLocation();

  const companiesDtoList = ref<CompaniesDtoList[]>([]);
  const personalHonorList = ref<string[]>([]);
  const socialIdentityList = ref<string[]>([]);
  const imgList = ref<string[]>([]);
  const briefIntroduction = ref('');

  const videoInfo = ref({
    tempFilePath: '',
    thumbTempFilePath: '',
  });

  const personalInfo = ref<PersonalInfoData>({
    name: '',
    socialPosition: '',
    phone: '',
    wechatId: '',
    email: '',
    avatar: '',
    wechatIdDisplay: 0,
    mobileDisplay: 0,
    emailDisplay: 0,
  });

  const getMasterDes = computed(() => {
    const data = companiesDtoList.value;
    return data.length && data[0].authentication ? '"主单位"内容请到"单位主页"编辑' : '';
  });

  const getAuthenticationEditPer = computed(() => {
    return (
      unref(cocInfo).memberRoleType === MemberRoleEnum.PRINCIPAL ||
      unref(cocInfo).memberRoleType === MemberRoleEnum.MANAGER
    );
  });

  let callback: () => void;
  const memberLeadingId = ref<number>();
  function __init(r: PersonalCardDetailsResult) {
    memberLeadingId.value = r.memberLeadingId;
    selected.value = [];
    personalInfo.value = {
      avatar: r.avatar,
      name: r.name,
      socialPosition: r.socialPosition,
      wechatId: r.wechatId,
      email: r.email,
      phone: r.phone,
      wechatIdDisplay: r.wechatIdDisplay,
      mobileDisplay: r.mobileDisplay,
      emailDisplay: r.emailDisplay,
    };
    personalHonorList.value = r.personalHonorList;
    socialIdentityList.value = r.socialIdentityList;
    (r.companiesDtoList || []).forEach((v) => {
      if (!v.authentication) {
        selected.value.push(v.id);
        temSelected.value.push(v.id);
      }
    });
    videoInfo.value.tempFilePath = r.video;
    videoInfo.value.thumbTempFilePath = r.videoCover;
    imgList.value = r.imgList;
    briefIntroduction.value = r.briefIntroduction;
    info.value = r;
  }

  const selectedProductIds = ref<number[]>([]);
  const isSubmitLoading = ref(false);
  const submit = () => {
    if (!personalInfo.value.name) return Toast('姓名不能为空', 'none', 1500);
    if (!info.value) return;
    const { id, leaderId } = info.value;
    if (isSubmitLoading.value) return;
    isSubmitLoading.value = true;
    const data: EditPersonalCardDetailsData = {
      id,
      leaderId,
      ...personalInfo.value,
      personalHonorList: personalHonorList.value,
      socialIdentityList: socialIdentityList.value,
      companiesDtoList: unitList.value.map((v) => ({
        id: v.id,
        isShow: selected.value.includes(v.id) ? 0 : 1,
        authentication: v.authentication,
      })),
      videoCover: videoInfo.value.thumbTempFilePath,
      video: videoInfo.value.tempFilePath,
      imgList: imgList.value,
      briefIntroduction: briefIntroduction.value,
      productLibIds: selectedProductIds.value,
    };

    editPersonalCardDetails(data)
      .then((r) => {
        callback?.();
        UniNavigateBack();
      })
      .catch((err) => {
        isSubmitLoading.value = false;
        logManager.error(err);
      });
  };

  function cancel() {
    interceptNavigateBack();
  }

  function toDel(i: number, id: number) {
    temSelected.value = [];
    const index = selected.value.findIndex((v) => v === id);
    if (index !== -1) selected.value.splice(index, 1);
    nextTick(() => (temSelected.value = unref(selected)));
  }

  function toEdit(id: number, authentication: boolean) {
    if (!authentication) {
      const item = unref(unitList).find((v) => v.id === id);
      navigateTo({
        name: 'editAffiliatedCompanies',
        options: {
          item,
          success: async () => {
            await useUser.setUnitList();
            getUnitList();
          },
        },
      });
    } else {
      navigateTo({
        name: 'editBusinessCard',
        options: {
          id,
          callback: callback,
        },
      });
    }
  }

  onLoad<'EditPersonCard'>(async (op) => {
    callback = op.callback;
    if (op.data) {
      await useUser.setUnitList();
      selectedProductIds.value = await getCardPersonalSelectedProductIds(op.data.memberLeadingId);
      __init(op.data);
      getUnitList();
    }
  });

  /** 分享图生成失败回调 */
  function posterFail(err: any) {
    console.error(err);
  }

  const unitLocaldata = ref<Localdata[]>([]);
  const selected = ref<number[]>([]);
  const temSelected = ref<number[]>([]);
  async function getUnitList() {
    unitLocaldata.value = [];
    unitList.value.forEach((v) => {
      if (v.id && !v.authentication) {
        unitLocaldata.value.push({
          text: v.name,
          value: v.id,
        });
      }
    });
  }

  /** 新增单位 */
  function addUnit() {
    navigateTo({
      name: 'editAffiliatedCompanies',
      options: {
        success: async () => {
          await useUser.setUnitList();
          getUnitList();
        },
      },
    });
  }

  const _this = getCurrentInstance();
  function openModel() {
    (_this?.refs['SelectUnits'] as any).open('bottom');
  }

  function closeModel() {
    selected.value = temSelected.value;
    (_this?.refs['SelectUnits'] as any).close();
  }

  const getCompaniesDtoList = computed(() => {
    return unitList.value.filter(
      (v) =>
        (selected.value.includes(v.id) || v.authentication) &&
        ({
          name: v.name,
          authentication: v.authentication,
          id: v.id,
        } as CompaniesDtoList),
    );
  });

  function maskClick() {
    temSelected.value = [];
    nextTick(() => (temSelected.value = unref(selected)));
  }

  function showTips() {
    uni.showModal({
      title: '提示',
      content: '如需修改单位名称，请前往【我的】-【入会资料】修改，修改后将会自动同步到此处。',
      showCancel: false
    })
  }
</script>
<style lang="scss">
  .edit-container .uni-easyinput__content-textarea {
    max-height: 600rpx;
  }
</style>
<style lang="scss" scoped>
  .container {
    margin-top: 10rpx;

    .affiliated-companies {
      &-item {
        height: 86rpx;
        border-top: 1px solid #dddddd;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .companies-name {
          font-size: 27rpx;
          display: flex;
          align-items: center;
          .tag {
            white-space: nowrap;
            font-size: 20rpx;
            padding: 5rpx 20rpx;
            margin-left: 10rpx;
            color: #fff;
            background-color: #ef823a;
            border-radius: 23rpx;
          }
        }
        .handle-btn-group {
          display: flex;
          align-items: center;
          .handle-btn {
            width: 32rpx;
            height: 32rpx;
            margin-left: 20rpx;
          }
        }
      }
    }
  }

  .select-units {
    border-radius: 32rpx 32rpx 0 0;
    padding: 0 32rpx;
    &--header {
      height: 96rpx;
      line-height: 96rpx;
      text-align: center;
      font-size: 32rpx;
      color: #333;
      position: relative;
      .add-btn {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 135rpx;
        height: 54rpx;
        border-radius: 10rpx;
        background-color: #e9e3b5;
        line-height: 54rpx;
        font-size: 24rpx;
        text-align: center;
      }
    }
    .unit-list {
      height: 400rpx;
      padding-bottom: 32rpx;
    }
  }
</style>
